﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using IsoStorageManagerLib;

namespace IsoStorageManagerApp
{
    // NOTE: For a real release, uncomment [Conditional("DEBUG")] attributes. Then all WriteLine() calls would be ignored.

    public class SimpleLogger
    {
        // Settings
        private const bool isSavedToFile = true; // Enable recording to file (useful for performance tests in Release)
        private const bool addDatastampToFileNames = true; // If true, file name would contain timestamp. WARNING: this would produce new file each run.

        private const string LOGNAME_PREFIX = "AppLog";
        private const string LOGNAME_POSTFIX = "txt";


        private static readonly string LOGNAME;
        private static DateTime lastLog;

        static SimpleLogger logger; // Singleton
        static SimpleLogger Logger
        {
            get { return logger ?? (logger = new SimpleLogger()); }
        }

        // TODO: implement bitwise filtering
        static SimpleLogger()
        {
            if (DesignerProperties.IsInDesignTool) return;

            lastLog = DateTime.UtcNow;

            if (addDatastampToFileNames)
                LOGNAME = String.Format("{0}_{1}.{2}", LOGNAME_PREFIX, lastLog.ToString("yyyy-MM-dd_HH-mm"), LOGNAME_POSTFIX);
            else
            {
                LOGNAME = String.Format("{0}.{1}", LOGNAME_PREFIX, LOGNAME_POSTFIX);
                IsoStorageManager.DeleteFile(LOGNAME);
            }

            Logger.Log("[!] Logger is constructed");
        }


        //[Conditional("DEBUG")]
        public static void WriteLine(object value)
        {
            Logger.Log((value == null) ? "(null)" : value.ToString());
        }

        //[Conditional("DEBUG")]
        public static void WriteLine(string format)
        {
            Logger.Log("{0}", format);
        }

        //[Conditional("DEBUG")]
        public static void WriteLine(string format, params object[] values)
        {
            Logger.Log(format, values);
        }


        private void Log(string format, params object[] values)
        {
            var nowStr = DateTime.UtcNow.ToString("hh:mm:ss.fff"); // Get current time first

            var formatted = String.Format(null, format, values);
            var deltaTime = DateTime.UtcNow.Subtract(lastLog);
            var deltaTimeStr = deltaTime.ToString(@"hh\:mm\:ss\.fff"); //ToString("hh:mm:ss.fff");

            var output = String.Format("{0} [{1}] {2}", nowStr, deltaTimeStr, formatted);

            Debug.WriteLine(output);

            if (isSavedToFile)
                IsoStorageManager.AppendFile(LOGNAME, output);

            lastLog = DateTime.UtcNow; // Store current time last to exclude logger overhead
        }
    }

}
